//
//  RecordIndexer.m
//  SimulacraDB
//
//  Created by Andre Cohen on 9/3/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "RecordIndexer.h"


@implementation RecordIndexer

@synthesize block;
@synthesize dataSource;

- (id)initIndexerByBlock:(int)recordBlock
			withFileName:(NSString *)filename
		   withDataSouce:(Paging *)source 
		 recordPrototype:(Record *)record {
	[super init];
	
	block = recordBlock;
	dataSource = source;
	prototype = record;
	
	file = [NSString stringWithFormat:@"%@_%02d",filename,recordBlock];
	[self load:file];
	
	return self;
}

- (void)close {
	[self save:file];
}

- (NSArray *)getRecord:(Record *)record {
	NSMutableArray *results = [[[NSMutableArray alloc] init] autorelease];
	BTreeNode *current = [self getLeafForRecord:record];
	int i;
	BOOL found = NO;
	while(YES){
		for(i=0;i<[[current keys] count];i++){
			Record *temp = [dataSource getRecordAt:[[[current keys] objectAtIndex:i] toRecordOfType:prototype]];
			if([record recordBlock:[self block] equalTo:temp]){
				[results addObject:temp];
				found = YES;
			}else if(found == YES)
				found=NO;
		}
		return results;
		if(found==NO){
			return results;
		}
		else if([[current edges] count]>0){
			current = [[current edges] objectAtIndex:0];
		}else{
			return results;
		}
	}
	return results;
}

- (BTreeNode *)getLeafForRecord:(Record *)record {
	BTreeNode *current = root;
	while([[current edges] count]>1){
		int i;
		BOOL next = NO;
		for(i=0;i<[[current keys] count] && !next;i++){
			IndexRecord *ir = [[current keys] objectAtIndex:i];
			Record *temp = [dataSource getRecordAt:[ir toRecordOfType:prototype]];
			if([record recordBlock:[self block] lessThan:[dataSource getRecordAt:temp]]){
				current = [[current edges] objectAtIndex:i];
				next = YES;
			}
		}
		if(next==NO)
			current = [[current edges] lastObject];
	}
	return current;
}

- (BOOL)isRecord:(IndexRecord *)a lessThan:(IndexRecord *)b{
	Record *rA = [dataSource getRecordAt:[a toRecordOfType:prototype]];
	Record *rB = [dataSource getRecordAt:[b toRecordOfType:prototype]];
	return [rA recordBlock:[self block] lessThan:rB];
}
- (BOOL)isRecord:(IndexRecord *)a greaterThan:(IndexRecord *)b{
	Record *rA = [dataSource getRecordAt:[a toRecordOfType:prototype]];
	Record *rB = [dataSource getRecordAt:[b toRecordOfType:prototype]];
	return [rA recordBlock:[self block] greaterThan:rB];
}
- (BOOL)isRecord:(IndexRecord *)a equalTo:(IndexRecord *)b {
	Record *rA = [dataSource getRecordAt:[a toRecordOfType:prototype]];
	Record *rB = [dataSource getRecordAt:[b toRecordOfType:prototype]];
	return [rA recordBlock:[self block] equalTo:rB];
}

@end
